// pages/menu/index.js
const { cakeApi,addressApi } = require('../../utils/api/index.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentCategoryId: null,
    categories: [],
    products: [],
    cartItems: [],
    totalQuantity: 0,
    totalPrice: 0,
    showCartPanel: false,
    showDetails: false,
    selectedProduct: null,
    initSpecs: [],
    initTasties:[],
    // 店铺位置信息
    shopLocation: {
      latitude: 22.274727,  // 纬度
      longitude: 113.450422,  // 经度
      makers:{
        id: 1,
        latitude: 22.274727,
        longitude: 113.450422,
        title: "四序cake • 蛋糕(中山坦洲店)",
      },
      showActionSheet: false,
      name: '四序cake • 蛋糕(中山坦洲店)',
      address: '广东省中山市坦洲镇永一村环洲北路(延伸)9号锦绣国际花城花和苑19卡'  //实际的地址
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.loadProductList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.queryShoppingCartCount();
    this.queryShoppingCartList();
    if(this.data.totalQuantity != 0){
      this.setData({ showCartPanel: true });
    };
    var tempProductId = wx.getStorageSync('tempProductId');
    if(null != tempProductId && "" != tempProductId){
      wx.removeStorageSync('tempProductId'); // 使用后清除
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  //加载分类产品列表
  async loadProductList() {
    try {
      const result = await cakeApi.queryCategory('1860141172396265472')
      if (result.code === '0000') {
        var categories = []
        var productList = [];
        var firstId = null;
        result.data.forEach(item => {
          if(firstId == null){
            firstId = item.categoryId
          }
          var category = {
            id: item.categoryId,
            name: item.categoryName
          }
          categories.push(category);
          if(item.productList != null){
            item.productList.forEach(p =>{
              var product = {
                id: p.productId,
                name: p.productName,
                description: p.tagline,
                price: p.price,
                image: p.images[0],
                categoryId: item.categoryId
              };
              productList.push(product);
            });
          }
        });
        this.setData({
          currentCategoryId: firstId,
          categories: categories,
          products: productList
        });
      }
    } catch (error) {
      console.error('加载产品列表失败：', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    }
  },

  // 切换分类
  switchCategory(e) {
    const categoryId = e.currentTarget.dataset.id;
    this.setData({
      currentCategoryId: categoryId
    });
  },

  // 显示商品详情
  async showDetails(e) {
    //查询产品详情
    try {
      const { product } = e.currentTarget.dataset;
      const result = await cakeApi.queryProductDetail(product.id);
      if (result.code === '0000') {
        var productDetail = result.data;
        var finalProduct = {
          id: productDetail.productId,
          name: productDetail.productName,
          description: productDetail.tagline,
          price: '￥'+productDetail.price+'~￥'+productDetail.maxPrice,
          image: productDetail.images[0],
          categoryId: productDetail.categoryId,
          thermalBagPrice: productDetail.thermalBagPrice
        };
        var specs = []
        var tasties = [];
        productDetail.specList.forEach(item => {
          var spec =  {
            id: item.specId,
            name: item.name,
            price: item.price,
            stock: 1000
          };
          specs.push(spec);
        });
        if(productDetail.tasteList != null){
          productDetail.tasteList.forEach(item => {
            var taste = {
              id: item.tasteId,
              name: item.tasteName
            };
            tasties.push(taste);
          });
        };
        this.setData({
          showDetails: true,
          selectedProduct: finalProduct,
          initSpecs: specs,
          initTasties: tasties
        });
      }
    } catch (error) {
      console.error('加载产品详情失败：', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    }
  },

  // 关闭商品详情
  closeDetails() {
    this.setData({
      showDetails: false,
      selectedProduct: null,
      initSpecs: [],
      initTasties: []
    });
  },

  // 添加商品到购物车
  addToCart(e) {
    const{ cartItem } = e.detail;
    //保存到后台
    this.addShoppingCart(cartItem);
    this.queryShoppingCartList();
    this.setData({ showCartPanel: true });
  },

  //查询购物车数量和总价
  async queryShoppingCartCount(){
    try {
      const param = {
        userId: '1837425962481504256'  //TODO 先写死，后续从token中拿  
      }
      const result = await cakeApi.queryShoppingCartCount(param);
      if (result.code === '0000') {
        var totalQuantity = result.data.totalNum;//购物车总数量
        var totalPrice = result.data.totalPrice; //购物车总金额
        this.setData({
          totalQuantity: totalQuantity,
          totalPrice: totalPrice
        });
      }else{
        wx.showToast({
          title: '获取购物车数量失败：'+ result.msg,
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('获取购物车数量失败：', error)
      wx.showToast({
        title: '获取购物车数量失败',
        icon: 'none'
      })
    }
  },

  //查询购物车明细
  async queryShoppingCartList(){
    try {
      const param = {
        userId: '1837425962481504256'  //TODO 先写死，后续从token中拿  
      }
      const result = await cakeApi.queryShoppingCartList(param);
      if (result.code === '0000') {
        var cartItems = result.data;//购物车所有的商品
        this.setData({
          cartItems
        });
      }else{
        wx.showToast({
          title: '查询购物车明细失败：'+result.msg,
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('查询购物车明细失败：', error)
      wx.showToast({
        title: '查询购物车明细失败',
        icon: 'none'
      })
    }
  },

  //保存购物车到后台
  async addShoppingCart(cartItem){
    try {
      const result = await cakeApi.addShoppingCart(cartItem);
      if (result.code === '0000') {
        wx.showToast({
          title: '添加购物车成功',
          icon: 'none'
        });
        this.queryShoppingCartCount();
      }else{
        wx.showToast({
          title: '添加购物车失败：'+result.msg,
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('添加购物车失败：', error)
      wx.showToast({
        title: '添加购物车失败',
        icon: 'none'
      })
    }
  },

  // 切换购物车面板
  toggleCart(e) {
    const { showCartPanel } = e.detail;
    this.setData({ showCartPanel });
  },

  // 清空购物车
   async clearCart() {
    try {
      const param = {
        userId: '1837425962481504256'  //TODO 先写死，后续从token中拿  
      }
      const result = await cakeApi.emptyShoppingCart(param);
      if (result.code === '0000') {
        this.setData({
          cartItems: [],
          totalQuantity: 0,
          totalPrice: 0,
          showCartPanel: false
        });
      }else{
        wx.showToast({
          title: '清空购物车失败：'+result.msg,
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('清空购物车失败：', error)
      wx.showToast({
        title: '清空购物车失败',
        icon: 'none'
      })
    }
  },

  //在购物车里面更新购物车数量
  async changeQuantity(e){
    const{ id,type } = e.detail;
    try{
      var quantity = 1;
      var totalQuantity = this.data.totalQuantity; //商品总数
      var totalPrice = this.data.totalPrice; //商品总价
      var cartItems = this.data.cartItems;
      cartItems.forEach(item => {
         if(item.cartId === id){
           if("increase" === type){
            quantity = item.quantity + 1;
            totalQuantity = totalQuantity + 1;
            totalPrice = totalPrice + item.price + item.thermalBagPrice;
           }
           if("decrease" === type){
            quantity = item.quantity - 1;
            totalQuantity = totalQuantity - 1;
            totalPrice = totalPrice - item.price - item.thermalBagPrice;
           }
           item.quantity = quantity;
         }
      });
      
      const param = {
        cartId: id,
        quantity: quantity
      }
      const result = await cakeApi.updateShoppingCart(param);
      if (result.code === '0000') {
        this.setData({
          cartItems: cartItems,
          totalQuantity: totalQuantity,
          totalPrice: totalPrice
        });
      }else{
        wx.showToast({
          title: '更新购物车数量失败'+result.msg,
          icon: 'none'
        })
      }
    }catch (error) {
      console.error('更新购物车数量失败：', error)
      wx.showToast({
        title: '更新购物车数量失败',
        icon: 'none'
      })
    }
  },

  // 去结算
  checkout() {
    if (this.data.cartItems.length === 0) {
      wx.showToast({
        title: '请先选择商品',
        icon: 'none'
      });
      return;
    }
    
    // 这里添加结算逻辑
    wx.navigateTo({
      url: '/pages/checkout/checkout'
    });
  },

  calculateTotal() {
    let totalQuantity = 0
    let totalPrice = 0
    
    this.data.cartItems.forEach(item => {
      totalQuantity += item.quantity
      totalPrice += item.quantity * item.price
    })
    
    this.setData({
      totalQuantity,
      totalPrice
    })
  },

  // 打开地图
  openLocation() {
    const { latitude, longitude, name, address } = this.data.shopLocation
     wx.openLocation({
       latitude,
       longitude,
       name,
       address,
       scale: 18
     });
  }
})